//
//  LoginViewController.m
//  跨界收
//
//  Created by MT on 2018/10/27.
//  Copyright © 2018年 gztx. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "TabBarController.h"
#import "AppDelegate.h"

@interface LoginViewController () <UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *phoneTf;
@property (weak, nonatomic) IBOutlet UITextField *codeTf;
@property (weak, nonatomic) IBOutlet UIButton *checkBtn;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;
@property(nonatomic,assign)int setAliasCount;
@property(nonatomic,copy)NSString *alias;

@end

@implementation LoginViewController

#pragma mark - Lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self setup];
}

#pragma mark - Routine
- (void)setup
{
    self.checkBtn.selected = YES;
    [self setupLoginEnabled];
    if (kInDeveloping) {
        self.phoneTf.text = @"18680471060";
    }
}

- (void)setupLoginEnabled
{
    UIColor *blue = [UIColor cz_colorWithHex:0x467CEE];
    UIColor *gray = [UIColor cz_colorWithHex:0xc7c7c7];
    BOOL enabled = (self.phoneTf.text.length > 0 || self.codeTf.text.length > 0);
    self.loginBtn.backgroundColor = enabled ?  blue: gray;
    self.loginBtn.enabled = enabled;
}

- (void)setupCountDown
{
    [self.codeBtn countdownTimerWithInterval:60 progressBlock:^(UIButton *sender, NSInteger time) {
        sender.userInteractionEnabled = NO;
        NSString *strTime = [NSString stringWithFormat:@"%.2d", (int)time];
        NSString *title = [NSString stringWithFormat:@"(%@s)",strTime];
        [sender setTitle:title forState:UIControlStateNormal];
    } successBlock:^(UIButton *sender) {
        sender.userInteractionEnabled = YES;
        [sender setTitle:@"获取验证码" forState:UIControlStateNormal];
    }];
}

- (BOOL)isValidMobile
{
    if (self.phoneTf.text.length == 0) {
        [self showInfo:@"请输入手机号"];
        return NO;
    }
    if (! [Tool IsPhoneNumber:self.phoneTf.text]) {
        [self showInfo:@"请输入正确的手机号"];
        return NO;
    }
    return YES;
}

- (BOOL)isValidInput
{
    if (! [self isValidMobile]) {
        return NO;
    }
    if (self.codeTf.text.length == 0) {
        [self showInfo:@"请输入验证码"];
        return NO;
    }
    if (! self.checkBtn.selected) {
        [self showInfo:[NSString stringWithFormat:@"请阅读并同意%@协议", kAppName]];
        return NO;
    }
    return YES;
}

- (void)closeKeyboard
{
    [self.phoneTf resignFirstResponder];
    [self.codeTf resignFirstResponder];
}

#pragma mark - Event
- (IBAction)getCode:(UIButton *)sender
{
    if (! [self isValidMobile]) {
        return;
    }
    [self requestForSMS];
}

- (IBAction)login:(UIButton *)sender
{
    if (! [self isValidInput]) {
        return;
    }
    [self closeKeyboard];
    [self requestForLogin];
}

- (IBAction)selecCheck:(UIButton *)sender
{
    sender.selected = !sender.selected;
}

- (IBAction)gotoRegister:(UIButton *)sender
{
    RegisterViewController *registerVC = [[RegisterViewController alloc] initWithNibName:@"RegisterViewController" bundle:nil];
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:registerVC];
    [self presentViewController:navi animated:YES completion:nil];
}

- (IBAction)textFieldEditingChanged:(UITextField *)sender
{
    [self setupLoginEnabled];
}

#pragma mark - Request
- (void)requestForSMS
{
    NSDictionary *parameters = @{ @"mobile": self.phoneTf.text, @"type": @(1) };
    [NetworkManager post:kSendSMSApi parameters:parameters success:^(id object) {
        [self showInfo:@"短信下发成功"];
        [self setupCountDown];
    } failure:^(NSError *error) {
        [self handleRequestFailure:error];
    }];
}

- (void)requestForLogin
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"account"] = self.phoneTf.text;
    dic[@"code"] = self.codeTf.text;
    [self showHUD];
    [NetworkManager post:kLoginApi parameters:dic success:^(id data) {
        [Tool setLocalDataValue:data[@"token"] key:kAccessTokenKey];
        [self requestForUserInfo];
    } failure:^(NSError *error) {
        [self hideHUD];
        [self handleRequestFailure:error];
    }];
}

- (void)requestForUserInfo
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"type"] = @(1);

    [NetworkManager post:kUserInfoApi parameters:dic success:^(id data) {
        NSLog(@"%@::login",data);
        UserModel *user = [UserModel modelWithJSON:data];
        [user saveToDisk];
        [[AppDelegate sharedDelegate] doLogin];
        [self showSuccess:@"登录成功"];
    } failure:^(NSError *error) {
        [self handleRequestFailure:error];
    }];
}

@end
